﻿using DotNetExtensions.Core.Autofac;
using DotNetExtensions.Core.IOC;
using DotNetExtensions.Core.Restful;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace Habi.Server.Middlewares
{
    [AutoInject(Kind = InjectKind.Named)]
    public class HandleExceptionMiddleware : IMiddleware
    {
        private readonly ILogger logger;
        public HandleExceptionMiddleware()
        {
            logger = LoggerFactory.Create(option =>
            {

            }).CreateLogger(typeof(HandleExceptionMiddleware));
        }

        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            try
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                context.Response.Headers.Add("Access-Control-Allow-Methods", "*");
                context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
            finally
            {
                logger.LogDebug($">{context.Request.Method} Url+{context.Request.Host}{context.Request.Path}");
            }
        }


        private Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            context.Response.ContentType = "application/json";

            context.Response.StatusCode = (int)HttpStatusCode.OK;
            return context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(ApiResult.Failed(ex.Message, null)), System.Text.Encoding.UTF8);
        }
    }
}
